<template>
  <transition-group name="notification" tag="div" class="fixed top-4 right-4 z-50 flex flex-col space-y-2">
    <div
      v-for="notification in notifications"
      :key="notification.id"
      :class="[
        'p-4 rounded shadow-md transition-all transform',
        `bg-${notification.type}-100 border border-${notification.type}-400 text-${notification.type}-700`
      ]"
    >
      <div class="flex justify-between">
        <div class="font-bold">{{ notification.title }}</div>
        <button @click="removeNotification(notification.id)" class="ml-4 text-gray-500 hover:text-gray-700">
          &times;
        </button>
      </div>
      <div class="mt-1">{{ notification.message }}</div>
    </div>
  </transition-group>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'

const notifications = ref([])
let nextId = 1

const addNotification = (title, message, type = 'info', timeout = 5000) => {
  const id = nextId++
  notifications.value.push({ id, title, message, type })
  
  if (timeout > 0) {
    setTimeout(() => {
      removeNotification(id)
    }, timeout)
  }
  
  return id
}

const removeNotification = (id) => {
  const index = notifications.value.findIndex(n => n.id === id)
  if (index !== -1) {
    notifications.value.splice(index, 1)
  }
}

// 将方法暴露给父组件
defineExpose({
  addNotification,
  removeNotification
})

// 全局事件处理
const handleNotification = (event) => {
  const { title, message, type, timeout } = event.detail
  addNotification(title, message, type, timeout)
}

onMounted(() => {
  window.addEventListener('notification', handleNotification)
})

onBeforeUnmount(() => {
  window.removeEventListener('notification', handleNotification)
})
</script>

<style scoped>
.notification-enter-active,
.notification-leave-active {
  transition: all 0.3s ease;
}
.notification-enter-from {
  opacity: 0;
  transform: translateX(30px);
}
.notification-leave-to {
  opacity: 0;
  transform: translateX(30px);
}
</style>